package com.sanjiahantang.youjiaclient.module.complain.views.impl;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sanjiahantang.uilibrary.popuwindow.SelectPhotoPopupwindow;
import com.sanjiahantang.uilibrary.utils.BitmapUtils;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.uilibrary.views.MyGridView;
import com.sanjiahantang.youjiaclient.R;
import com.sanjiahantang.youjiaclient.base.BaseMvpActivity;
import com.sanjiahantang.youjiaclient.base.BaseView;
import com.sanjiahantang.youjiaclient.config.ConfigValue;
import com.sanjiahantang.youjiaclient.config.SPConfig;
import com.sanjiahantang.youjiaclient.module.common.beans.FileBean;
import com.sanjiahantang.youjiaclient.module.common.models.impl.UserModel;
import com.sanjiahantang.youjiaclient.module.complain.presenters.ComplainPresenter;
import com.sanjiahantang.youjiaclient.module.complain.views.ComplainView;
import com.sanjiahantang.youjiaclient.module.decorate.beans.DecorateManageBean;
import com.sanjiahantang.youjiaclient.module.goods.beans.GoodsBean;
import com.sanjiahantang.youjiaclient.utils.FileUtils;
import com.sanjiahantang.youjiaclient.utils.SPUtils;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by zy on 2017/9/11.
 */

public class ComplainActivity extends BaseMvpActivity<ComplainView, ComplainPresenter> implements ComplainView, View.OnClickListener {
    private MyGridView gvImageList;
    private DecorateManageBean.Data decorateData;
    private int maxId;
    private BaseAdapter adapter;
    private List<GoodsBean.Image> imageList;
    private LayoutInflater inflater;
    private final static int INTENT_ROLE = 200;
    private View panelRole;
    private EditText activity_complain_describe_et;
    private DecorateManageBean.Role role;
    private int complainRole;

    private SelectPhotoPopupwindow photoPopupwindow;
    private View rootView;

    protected static final int CHOOSE_PICTURE = 0;
    protected static final int TAKE_PICTURE = 1;
    private static final int CROP_SMALL_PICTURE = 2;
    private static final int UPLOAD_PIC = 3;
    private static final int PHOTO_GRAPH = 0xF, SELECT_PICTURE = 3, INTENT_NICKNAME = 5, SAVE_PHOTO = 6;

    @Override
    public void showProgress() {
        super.showProgress($this);
    }

    @Override
    public ComplainPresenter initPresenter() {
        return new ComplainPresenter();
    }

    @Override
    public void initView() {
        setContentView(R.layout.activity_complain);
        inflater = LayoutInflater.from($this);
        gvImageList = (MyGridView) findViewById(R.id.gvImageList);
        rootView = findViewById(R.id.rootView);

        TextView title = (TextView) findViewById(R.id.title);
        title.setText("投诉");

        findViewById(R.id.fl_Left).setOnClickListener(this);
        panelRole = findViewById(R.id.panelRole);

        RelativeLayout confirm = (RelativeLayout) findViewById(R.id.activity_complain_confirm_rl);
        confirm.setOnClickListener(this);

        activity_complain_describe_et = (EditText) findViewById(R.id.activity_complain_describe_et);

        decorateData = (DecorateManageBean.Data) getIntent().getSerializableExtra(KEY_PARAM);
        if (decorateData == null) {
            Utils.showToast($this, "初始化信息错误");
            finish();
            return;
        } else {
            presenter.findMaxId($this, new OnLoadListener() {
                @Override
                public void onLoad(Object content) {
                    if (content != null && content instanceof Integer) {
                        maxId = (int) content;
                    }
                }
            });
        }
        imageList = new ArrayList<>();
        adapter = new BaseAdapter() {
            @Override
            public int getCount() {
                return imageList.size() + 1;
            }

            @Override
            public Object getItem(int i) {
                return i == getCount() - 1 ? null : imageList.get(i);
            }

            @Override
            public long getItemId(int i) {
                return i;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup viewGroup) {
                ViewHolder holder = null;
                if (position < imageList.size()) {
                    convertView = inflater.inflate(R.layout.item_image, null);
                } else {
                    convertView = inflater.inflate(R.layout.item_add_image, null);
                }

                holder = new ViewHolder(convertView);
                holder.bind(getItem(position));

                return convertView;
            }
        };
        gvImageList.setAdapter(adapter);

        findViewById(R.id.panelComplainedRole).setOnClickListener(this);
        photoPopupwindow = new SelectPhotoPopupwindow($this, this);
    }

    @Override
    public void initData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fl_Left:
                finish();
                break;
            case R.id.panelComplainedRole:case R.id.panelRole:
                startActivityForResult(new Intent($this, ComplainRoleListActivity.class)
                        .putExtra(KEY_PARAM, decorateData), INTENT_ROLE
                );
                break;
            case R.id.activity_complain_confirm_rl:
                if (role == null) {
                    Utils.showToast($this, this.getString(R.string.complain_account_name_not_null));
                } else if (activity_complain_describe_et.getText().toString().isEmpty()) {
                    Utils.showToast($this, this.getString(R.string.complain_describe_not_null));
                }else {
                    presenter.addCustomerComplaint(this,
                            maxId + "", decorateData.getCustomerPhone(),decorateData.getCustomerName(),
                            role.getPhone(), role.getUserName(), complainRole + "", decorateData.getPiId() + "",
                            activity_complain_describe_et.getText().toString()
                    );
                }
                break;
            //拍照
            case R.id.btn_take_photo:
                photoPopupwindow.dismiss();
                if (ContextCompat.checkSelfPermission($this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        requestPermissions(new String[]{Manifest.permission.CAMERA}, 1);
                    }
                } else {
                    takePicture();
                }
                break;
            //相册
            case R.id.btn_pick_photo:
                photoPopupwindow.dismiss();
                presenter.cardSelect($this);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case INTENT_SELECT_PIC:
                    Uri uri0 = data.getData();
                    presenter.doUploadComplainPic($this, uri0, maxId, new BaseView.OnLoadListener() {
                        @Override
                        public void onLoad(Object content) {
                            FileBean.Data img = (FileBean.Data) content;
                            GoodsBean.Image bean = new GoodsBean.Image();
                            bean.setId(img.getPlanId());
                            bean.setUrl(img.getUrl());
                            imageList.add(bean);
                            adapter.notifyDataSetChanged();
                        }
                    });

                    break;
                case PHOTO_GRAPH:
                    if (data != null){
                        Bundle b = data.getExtras();
                        Bitmap bitmap = (Bitmap) b.get("data");
                        bitmap = BitmapUtils.resizeBitmap(bitmap, 480);
                        presenter.doUploadComplainPic($this, bitmap, maxId, new BaseView.OnLoadListener() {
                            @Override
                            public void onLoad(Object content) {
                                FileBean.Data img = (FileBean.Data) content;
                                GoodsBean.Image bean = new GoodsBean.Image();
                                bean.setId(img.getPlanId());
                                bean.setUrl(img.getUrl());
                                imageList.add(bean);
                                adapter.notifyDataSetChanged();
                            }
                        });

                    }else{
                        Utils.showToast($this,"请从相册选择图片");
                    }
                    break;
                case INTENT_ROLE:
                    Bundle bundle = data.getBundleExtra(KEY_PARAM);
                    role = (DecorateManageBean.Role) bundle.getSerializable(KEY_OBJECT);
                    complainRole = bundle.getInt(KEY_ROLE_CODE);
                    panelRole.setVisibility(View.VISIBLE);
                    panelRole.setOnClickListener(this);
                    ImageView ivPhoto = (ImageView) panelRole.findViewById(R.id.iv_image);
                    Picasso.with($this).load(FileUtils.rePath(role.getUrl()))
                            .placeholder(R.drawable.i_head_default)
                            .into(ivPhoto);
                    panelRole.setBackgroundColor(Color.WHITE);
                    TextView name = (TextView) panelRole.findViewById(R.id.name);
                    name.setText(role.getUserName());
                    TextView phone = (TextView) panelRole.findViewById(R.id.phone);
                    phone.setText(role.getPhone());

                    TextView roleName = (TextView) panelRole.findViewById(R.id.time);
                    String role = "项目经理";
                    switch (complainRole){
                        case 2:
                            role = "项目经理";
                            break;
                        case 3:
                            role = "监理";
                            break;
                    }
                    roleName.setText(role);
                    break;
            }
        }
    }


    private class ViewHolder {
        private View itemView;

        public ViewHolder(View itemView) {
            this.itemView = itemView;
        }

        public void bind(Object obj) {
            if (obj instanceof GoodsBean.Image) {
                final GoodsBean.Image img = (GoodsBean.Image) obj;
                ImageView iv = (ImageView) itemView.findViewById(R.id.image);
                Picasso.with($this).load(FileUtils.rePath(img.getUrl())).into(iv);
                iv.setTag(R.id.decode, img);
                View v = itemView.findViewById(R.id.ivClose);
                v.setVisibility(View.VISIBLE);
                v.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        presenter.deleteImage($this, img.getId(), new BaseView.OnLoadListener() {
                            @Override
                            public void onLoad(Object content) {
                                removePic((int) content);
                            }
                        });
                    }
                });

                iv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Utils.showPicDialog($this,FileUtils.rePath(img.getUrl()),R.drawable.i_rect_bg);
                    }
                });
            } else {
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        photoPopupwindow.showAtLocation(rootView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                    }
                });
            }

        }
    }

    private void removePic(int id) {
        for (GoodsBean.Image pic : imageList) {
            if (pic.getId() == id) {
                imageList.remove(pic);
                adapter.notifyDataSetChanged();
                break;
            }
        }
    }

    private void takePicture(){
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            try{
                startActivityForResult(takePhotoIntent, PHOTO_GRAPH);
            }catch (Exception e){
                e.printStackTrace();
                Utils.showToast($this,"请从相册上传图片");
            }
        } else
            Utils.showToast($this, "未插入SD卡");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                takePicture();
            } else {
                Utils.showToast(this, "权限被禁止，相关功能无法使用！");
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }
}
